<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit" :selfUpdate="true">
        <a-tabs :activeKey="tabKey" :tabBarStyle="{ marginBottom: '30px' }" @change="handleTabs">
          <a-tab-pane :key="0" tab="基本信息"></a-tab-pane>
          <a-tab-pane :key="1" tab="规格/库存"></a-tab-pane>
          <a-tab-pane :key="2" tab="商品详情"></a-tab-pane>
          <a-tab-pane :key="3" tab="更多设置"></a-tab-pane>
        </a-tabs>
        <div class="tabs-content">
          <!-- 基本信息 -->
          <div class="tab-pane" v-show="tabKey == 0">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品分类">
              <a-cascader
                  v-decorator="['catNo', { rules: [{ required: true, message: '请至少选择1个商品分类'  }] }]"
                  :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                  :options="formData.categoryList"
                  placeholder="选择分类"
              ></a-cascader>
              <div class="form-item-help">
                <router-link :to="{ path: '/product/category/index' }" target="_blank">去新增</router-link>
                <a href="javascript:void (0);" @click="onReloadCategoryList">刷新</a>
              </div>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌">
              <a-select
                  v-decorator="['brandNo', { rules: [{ required: true, message: '请至少选择1个商品品牌'  }] }]"
                  :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                  :options="formData.brandList"
                  placeholder="选择品牌"
              ></a-select>
              <div class="form-item-help">
                <router-link :to="{ path: '/product/brand/index' }" target="_blank">去新增</router-link>
                <a href="javascript:void (0);" @click="onReloadBrandList">刷新</a>
              </div>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品名称">
              <a-input
                  v-decorator="['productName', { rules: [{ required: true, min: 2, message: '请输入至少2个字符'  }] }]"
                  placeholder="请输入商品名称"
              />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品备注">
              <a-textarea
                  v-decorator="['remark']"
                  :autoSize="{ minRows: 4 }"
              />
            </a-form-item>
            <a-form-item
                :labelCol="labelCol" :wrapperCol="wrapperCol"
                label="商品主图"
            >
              <template v-slot:extra>
                <span class="extra">第一张为商城展示主图,请务必上传高清白底正面图</span>
                <p class="extra c-red">主图(上传至少三张起；上传尺寸800x800；首张必须为白底图，文件大小不超过5MB)</p>
              </template>
              <SelectImage
                  v-decorator="['mainImages', { rules: [{ required: true, message: '请至少上传1张商品图片'  }] }]"
                  :maxNum="10"
                  :default-list="getMainList(formData.product.images).map(i=>{return {cdnUrl: i}})"
                  :multiple="true"
              />
            </a-form-item>
            <a-form-item
                :labelCol="labelCol" :wrapperCol="wrapperCol"
                label="商品详情图"
            >
              <template v-slot:extra>
                <span class="extra">第一张为商城展示主图,请务必上传高清白底正面图</span>
                <p class="extra c-red">详情图为商城商品页下方详细信息长图,
                  详情图(上传至少一张起；上传图片宽度为750，最佳效果790，高度不限，文件大小不超过5MB)</p>
              </template>
              <SelectImage
                  v-decorator="['detailImages', { rules: [{ required: true, message: '请至少上传1张商品图片'  }] }]"
                  :default-list="getDetailList(formData.product.images).map(i=>{return {cdnUrl: i}})"
                  :maxNum="10"
                  :multiple="true"
              />
            </a-form-item>
          </div>

          <!-- 规格/库存 -->
          <div class="tab-pane" v-show="tabKey == 1">
            <MultiSpec
                ref="MultiSpec"
                :defaultSkuList="formData.product.details"
                :defaultSpecList="formData.product.specs"
            />
            <a-form-item label="库存计算方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group
                  v-decorator="['deductStockType', { initialValue: DeductStockType.ORDER.key, rules: [{ required: true }] }]"
              >
                <a-radio v-for="(item, index) in DeductStockType.data" :key="index" :value="item.key">
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
                label="商品限购"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                extra="用于限制每人购买该商品的数量"
            >
              <a-radio-group
                  v-decorator="['restrict', { initialValue: 0, rules: [{ required: true }] }]"
                  @change="onForceUpdate()"
              >
                <a-radio :value="0">关闭</a-radio>
                <a-radio :value="1">开启</a-radio>
              </a-radio-group>
              <div class="mt-10" v-if="form.getFieldValue('is_restrict')">
                <a-form-item>
                  <span class="mr-10">总限购</span>
                  <a-input-number
                      :min="1"
                      :precision="0"
                      v-decorator="['restrictTotal', { rules: [{ required: true, message: '请输入总限购数量' }] }]"
                  />
                  <span class="ml-10">件/人</span>
                </a-form-item>
                <a-form-item>
                  <span class="mr-10">每单限购</span>
                  <a-input-number
                      :min="1"
                      :precision="0"
                      v-decorator="['restrictSingle', { rules: [{ required: true, message: '请输入每单限购数量' }] }]"
                  />
                  <span class="ml-10">件/人</span>
                </a-form-item>
              </div>
            </a-form-item>
          </div>
          <!-- 商品详情 -->
          <div class="tab-pane" v-show="tabKey == 2">
            <a-form-item label="商品详情" :labelCol="labelCol" :wrapperCol="{span: 16}">
              <Ueditor
                  v-decorator="['desc', { rules: [{ required: true, message: '商品详情不能为空' }] }]"
              />
            </a-form-item>
          </div>

          <!-- 更多设置 -->
          <div class="tab-pane" v-show="tabKey == 3">
            <a-form-item
                label="商品卖点"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                extra="一句话简述，例如：此款商品美观大方 性价比较高 不容错过"
            >
              <a-input v-decorator="['sellingPoint']" placeholder="请输入商品卖点"/>
            </a-form-item>
            <a-form-item
                label="初始销量"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                extra="用户端展示的销量 = 初始销量 + 实际销量"
            >
              <a-input-number v-decorator="['salesInitial', { initialValue: 0}]"/>
            </a-form-item>
          </div>
        </div>
        <a-form-item class="mt-20" :wrapperCol="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit" :loading="isBtnLoading">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import * as ProductApi from '@/api/product'
import {InputNumberGroup, SelectImage, Ueditor} from '@/components'
import ProductModel from '@/common/model/product/Index'
import {MultiSpec} from './modules'
import {isEmptyObject} from '@/utils/util'
import {getDetailList, getMainList} from "@/common/enum/product/ImageType";
import {DeductStockTypeEnum} from '@/common/enum/product'

export default {
  components: {
    SelectImage,
    Ueditor,
    InputNumberGroup,
    MultiSpec
  },
  data() {
    return {
      // 默认的标签索引
      tabKey: 0,
      // 标签布局属性
      labelCol: {span: 3},
      // 输入框布局属性
      wrapperCol: {span: 9},
      // loading状态
      isLoading: false,
      isBtnLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 商品编码
      spu: null,
      // 表单数据
      formData: ProductModel.formData
    }
  },
  computed: {
    DeductStockType() {
      return DeductStockTypeEnum;
    }
  },
  created() {
    // 初始化数据
    this.initData()
  },
  beforeDestroy() {
    // 销毁商品详情
    ProductModel.formData.product = {}
  },
  methods: {
    getDetailList,
    getMainList,

    // 初始化数据
    initData() {
      // 记录商品ID
      this.spu = this.$route.query.spu
      // 获取form所需的数据
      this.isLoading = true
      ProductModel.getFromData(this.spu)
          .then(() => {
            // 商品表单数据
            if (!isEmptyObject(this.form.getFieldsValue())) {
              // 第一次赋值
              this.form.setFieldsValue(ProductModel.getFieldsValue())
              // 第二次赋值 (适用于动态渲染的form-item)
              this.$nextTick(() => {
                this.form.setFieldsValue(ProductModel.getFieldsValue2())
                this.onForceUpdate()
              })
            }
            this.isLoading = false
          })
    },

    // 手动强制更新页面
    onForceUpdate(bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },

    // 切换tab选项卡
    handleTabs(key) {
      this.tabKey = key
    },

    // 刷新分类列表
    onReloadCategoryList() {
      this.isLoading = true
      ProductModel.getCategoryList().then(() => {
        this.isLoading = false
      })
    },

    // 刷新品牌列表
    onReloadBrandList() {
      this.isLoading = true
      ProductModel.getBrandList().then(() => {
        this.isLoading = false
      })
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {form: {validateFields}} = this
      validateFields((errors, values) => {
        // 定位到错误的tab选项卡
        if (errors) {
          this.onTargetTabError(errors)
          return false
        }
        const MultiSpec = this.$refs.MultiSpec
        if (!MultiSpec.verifyForm()) {
          this.tabKey = 1
          return false
        }
        // 记录多规格数据
        values.specs = MultiSpec.getFromSpecData().specList
        values.details = MultiSpec.getFromSpecData().skuList
        // 整理商品分类
        values.catNo = values.catNo.at(-1)
        // 提交到后端api
        this.onFormSubmit(values)
        return true
      })
    },

    // 定位到错误的tab选项卡
    onTargetTabError(errors) {
      // 表单字段与tabKey对应关系
      // 只需要必填字段就可
      const tabsFieldsMap = [
        ['catNo', 'brandNo', 'productName', 'remark'],
        ['deductStockType', 'restrict', 'restrict_total', 'restrict_single'],
        ['desc'],
        []
      ]
      const field = Object.keys(errors).shift()
      for (const key in tabsFieldsMap) {
        if (tabsFieldsMap[key].indexOf(field) > -1) {
          this.tabKey = parseInt(key)
          break
        }
      }
    },

    // 提交到后端api
    onFormSubmit(values) {
      this.isLoading = true
      this.isBtnLoading = true
      ProductApi.edit(this.spu, values)
          .then(result => {
            // 显示提示信息
            this.$message.success('操作成功', 1.5)
            // 跳转到列表页
            setTimeout(() => {
              this.$router.push('./index')
            }, 1500)
          })
          .catch(() => {
            this.isBtnLoading = false
          })
          .finally(() => this.isLoading = false)
    }

  }
}

</script>
<style lang="less" scoped>
@import './style.less';
</style>
